/*
 * @Author: weidewei
 * @Date: 2025-11-25 09:33:02
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-25 10:26:56
 * @Description:
 * @FilePath: \2025-front-face\vite-react-ts-template\src\utils\dict.ts
 */
// 按照键，删除对应的键值对 delete
// 循环每一个键值对 forEach
// 得到当前键值对的数量 size
// 判断某个键是否存在 has
// 重新设置某个键对应的值，如果不存在，则添加 set

type Callback<K, V> = (key: K, val: V) => void;

export class Dict<K, V> {
  private keys: K[] = [];
  private vals: V[] = [];

  set(key: K, val: V) {
    const index = this.keys.indexOf(key);
    if (index < 0) {
      this.keys.push(key);
      this.vals.push(val);
    } else {
      this.vals[index] = val;
    }
  }

  delete(key: K) {
    const index = this.keys.indexOf(key);
    if (index < 0) return;
    this.keys.splice(index, 1);
    this.vals.splice(index, 1);
  }

  has(key: K) {
    return this.keys.includes(key);
  }

  forEach(callback: Callback<K, V>) {
    for(let i=0;i<this.keys.length;i++) {
        const val = this.vals[i];
        callback(this.keys[i],val);
    }
  }

  get dictSize() {
    return this.keys.length;
  }
}
